import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Cookies from 'js-cookie'
import elementEnLocale from 'element-ui/lib/locale/lang/en'
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'
import enLocale from './lang/en'
import zhLocale from './lang/zh-CN'
import store from '@/store'

Vue.use(VueI18n)

const messages = {
  en: {
    ...enLocale,
    ...elementEnLocale
  },
  'zh-CN': {
    ...zhLocale,
    ...elementZhLocale
  }
}

// 获取语言设置
export function getLanguage() {
  // 优先从cookie获取
  const language = Cookies.get('language')
  if (language) return language

  // 其次从浏览器获取
  const browserLanguage = navigator.language
  const locales = Object.keys(messages)
  for (const locale of locales) {
    if (browserLanguage.indexOf(locale) > -1) {
      return locale
    }
  }

  // 默认返回中文
  return 'zh-CN'
}

const i18n = new VueI18n({
  locale: getLanguage(),
  messages,
  silentTranslationWarn: true
})

// 在store初始化后同步语言设置
export function setI18nLanguage(lang) {
  i18n.locale = lang
  return lang
}

export default i18n
